package com.nf.health.app.customview;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.activity.miansearch.adapter.DefaultSelectCallback;
import com.nf.health.app.activity.miansearch.adapter.ListLeftAreaAdapter;
import com.nf.health.app.activity.miansearch.adapter.ListRightAreaSecondAdapter;
import com.nf.health.app.activity.miansearch.impl.OnChecktemLinstener;
import com.nf.health.app.activity.miansearch.impl.RecordPositionModel;
import com.nf.health.app.service.ServiceData;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.ViewUtil;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;

//import android.view.ViewGroup.LayoutParams;


/**
 * 只显示文字的工具类
 * 目前在登录的时候用到
 * @author yyh
 */
public class ShowMyTextSearchPopupWindow extends PopupWindow implements PopupWindow.OnDismissListener,AdapterView.OnItemClickListener,View.OnClickListener{
    private ListView lv_left_view,lv_right_view;
    private LinearLayout ll_content_search_view;
    private View mMenuView;
    private Context cnt;
    private int screenWidth = 0;
    private int screenHeight = 0;
    private View view_blank;
    private ListLeftAreaAdapter listLeftAreaAdapter;
    private ListRightAreaSecondAdapter listRightAreaSecondAdapter;
    private LinkedList<String> firstMenuList ;
    private LinkedList<String> secondMenuList ;
    private LinkedHashMap<String,LinkedList<String>> hashMap;
    private boolean isOpenLoadtion = false;//是不是开启定位
    private String locationAddress = "";//定位的地址
    /**** 是否是第一次进入,用于判断刚进入此界面时显示默认的listView中的条目 *******/
    private boolean flag = true;
    /*** 当前点击的一级条目 *****/
    private int nowPosition = 0;
    /*** 当前点击的二级条目 *****/
    private int nowSecondPosition = 0;
    /*********记录耳机菜单是否被点击过*******/
    private boolean isRecondForgenPosition =  false;
    /************用于记录选中条目的搜索值及其文字***********/
    private RecordPositionModel recordPositionModel = new RecordPositionModel();
    public ShowMyTextSearchPopupWindow(Activity context) {
        cnt = context;
        initData(DensityUtil.getScreenIntWidth(cnt),DensityUtil.getScreenIntHeight(cnt));
    }
    /**
     *
     * @param context 上下文对象
     */
    public ShowMyTextSearchPopupWindow(Activity context, int width, int height) {/*,int width,int height*/
        super(context);
        cnt = context;
        initData(width,height);
    }
    private void initData(int width, int height){
        setAnimationStyle(R.style.anim_menu_bottombar);
        LayoutInflater inflater = (LayoutInflater) cnt
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.showmytexttippopupwindow, null);
        mMenuView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        //popwin_layout.xml的根Layout必须为LinearLayout；如果为RelativeLayout的话， 代码出现空指针错误，导致程序崩溃
        lv_left_view = (ListView) mMenuView.findViewById(R.id.lv_left_view);
        lv_right_view = (ListView) mMenuView.findViewById(R.id.lv_right_view);
        ll_content_search_view = (LinearLayout) mMenuView.findViewById(R.id.ll_content_search_view);
        view_blank =  mMenuView.findViewById(R.id.view_blank);

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        //this.setWidth(LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        //this.setHeight(LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        //this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        screenWidth = DensityUtil.getScreenIntWidth(cnt);
        screenHeight = DensityUtil.getScreenIntHeight(cnt);
        this.setWidth(width);
        this.setHeight(height);
        this.setBackgroundDrawable(dw);
        setOutsideTouchable(false);
    /*    WindowManager.LayoutParams lp = (Activity)getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().setAttributes(lp);*/
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.ll_content_pop).getTop();
                int y=(int) event.getY();
                if(event.getAction()==MotionEvent.ACTION_UP){
                    if(y<height){
                        dismiss();
                    }
                }
                return true;
            }
        });
        setMyContentViewSisibile(1);
        setOnDismissListener(this);
        lv_right_view.setOnItemClickListener(this);
        lv_left_view.setOnItemClickListener(this);
        view_blank.setOnClickListener(this);
        view_blank.setAlpha(0.1f);
    }
    public ShowMyTextSearchPopupWindow setMyContentViewSisibile(int i){
        switch (i){
            case 1://显示ListView
                break;

            case 2://显示其他
                break;
        }
        return this;
    }

    /**
     * 设置popopwindow
     */
    public ShowMyTextSearchPopupWindow setMyLayputParams(double wf,double hf){
        int winth = (int) (wf * screenHeight);
        int height  = (int) (hf * screenHeight);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(winth);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(height);
        return this;
    }
    public ShowMyTextSearchPopupWindow setMyLayputParams2(int winth,int height){
        this.setWidth(winth);
        this.setHeight(height);
        return this;
    }

    /**
     * 设置popupwindow的位置
     * @param parent
     * @param gravity
     * @param x
     * @param y
     * @return
     */
    public ShowMyTextSearchPopupWindow setMypopupPosition(View parent, int gravity, int x, int y){
        showAtLocation(parent, gravity, x, y);
        return this;
    }
    public ShowMyTextSearchPopupWindow setMypopupPosition2(View parent, int x, int y){
        showAsDropDown(parent, x, y);
        return this;
    }





    /**
     * 设置弹出位置
     */
    public ShowMyTextSearchPopupWindow setMyCostomPosition(PopupEm popupEm,View view,int xoff, int yoff) {
        switch (popupEm){
            case bottom://从上部弹出来
                showAsDropDown(view,xoff,yoff);
                break;
        }
        return this;
    }
    private TextView tv_search_area,  tv_search_ks, tv_search_service;
    public ShowMyTextSearchPopupWindow initMyTextViewStatus(TextView tv_search_area, TextView tv_search_ks,TextView tv_search_service,boolean isOpenLoadtion){
        this.tv_search_area =tv_search_area;
        this.tv_search_ks =tv_search_ks;
        this.tv_search_service =tv_search_service;
        this.isOpenLoadtion =isOpenLoadtion;
        return this;
    }
    public ShowMyTextSearchPopupWindow setShowMyTextViewStatus(TextView tv_search_area, TextView tv_search_ks,TextView tv_search_service){
        this.tv_search_area =tv_search_area;
        this.tv_search_ks =tv_search_ks;
        this.tv_search_service =tv_search_service;

        return this;
    }
    @Override
    public void onDismiss() {//iv_blue_arrowup  inquiey_detail_arrowdown
        /*if(isOpenLoadtion){
            ViewUtil.setTextImgBackground3(tv_search_area, cnt,0,R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
        }else{
            ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,0, R.drawable.inquiey_detail_arrowdown, 0);
        }*/
        if(!TextUtils.isEmpty(locationAddress)){
            if(locationAddress.contains(firstMenuList.get(nowPosition))){
                if(tv_search_area.getText().equals("全国")){
                    ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,  0, R.drawable.inquiey_detail_arrowdown, 0);
                }else{
                    ViewUtil.setTextImgBackground3(tv_search_area, cnt,0,R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
                }
            }else{
                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,  0, R.drawable.inquiey_detail_arrowdown, 0);
            }
        }else{
            ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,  0, R.drawable.inquiey_detail_arrowdown, 0);
        }
        ViewUtil.setTextImgBackground2(tv_search_ks, cnt, ViewUtil.TextMode.RIGHT, 0, R.drawable.inquiey_detail_arrowdown);
        ViewUtil.setTextImgBackground2(tv_search_service, cnt, ViewUtil.TextMode.RIGHT, 0, R.drawable.inquiey_detail_arrowdown);
        tv_search_area.setTextColor(cnt.getResources().getColor(R.color.gray));
        tv_search_ks.setTextColor(cnt.getResources().getColor(R.color.gray));
        tv_search_area.setTextColor(cnt.getResources().getColor(R.color.gray));
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(parent == lv_left_view){//一级菜单
            String city = firstMenuList.get(position);
            if(position == 0){
                nowPosition = ServiceData.getCityDefaultPosition(hashMap, locationAddress);
                recordPositionModel.setLocalAddress(locationAddress);
                recordPositionModel.setSelectAddress(locationAddress);
            }else{
                recordPositionModel.setSelectAddress(city);
                nowPosition = position;
            }
            secondMenuList = hashMap.get(city);
            recordPositionModel.setIndex(-1);
            initSecondMenuList(nowPosition);
            //解决ListView的setSelsection不起作用的问题
            lv_left_view.post(new Runnable() {
                @Override
                public void run() {
                    //lv_left_view.requestFocusFromTouch();//获取焦点
                    //设置当前点击的条目显示在第一个条目 的位置
                    // lv_left_view.setSelection(nowPosition);
                }
            });
            if(position == 0){
                if(onChecktemLinstener != null){
                    onChecktemLinstener.onClickFirstMenu(city);
                }
                dismiss();
            }
        }else if(parent == lv_right_view){//二级菜单
            this.nowSecondPosition = position;
            String result = secondMenuList.get(position);//城市
            String city = firstMenuList.get(nowPosition);//省
            recordPositionModel.setSelectAddress(city);
            recordPositionModel.setLocalAddress(city);
            recordPositionModel.setIndex(nowSecondPosition);
            recordPositionModel.setLocationIndex(nowSecondPosition);
            if(onChecktemLinstener != null){
                onChecktemLinstener.onClickSecondMenu(city+ "|"+result);
            }
            isRecondForgenPosition = true;
            dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.view_blank:
                if(isShowing()){
                    dismiss();
                }
                break;
        }
    }

    public enum PopupEm{
        top,
        left,
        right,
        bottom
    }

    public void setMyListData2(LinkedHashMap<String,LinkedList<String>> hashMap,String locationAddress,boolean isOpenLoadtion){
        this.hashMap = hashMap;
        /*if(hashMap == null){
            hashMap = new LinkedHashMap<>();
            LinkedList<String> list = new LinkedList<>();
            list.add("全部地区");
            hashMap.put("全国", list);
        }*/
        firstMenuList =  new LinkedList<>(hashMap.keySet());
        this.isOpenLoadtion = isOpenLoadtion;
        this.locationAddress = locationAddress;
        nowPosition = ServiceData.getCityDefaultPosition(hashMap, locationAddress);
        if(!TextUtils.isEmpty(locationAddress)){
            if(locationAddress.contains("|")){
                String locationAddressStr[] =locationAddress.split("\\|");
                String str =locationAddressStr[2];
                if(!TextUtils.isEmpty(str)){
                    nowSecondPosition  = Integer.parseInt(str);
                    recordPositionModel.setLocalAddress(locationAddressStr[0]);//临时记录定位下来的地址
                    recordPositionModel.setSelectAddress(locationAddressStr[0]);//第一次进入时定位地址的二级索引=定位的二级菜单的索引
                    recordPositionModel.setIndex(nowSecondPosition);//第一次进入时定位地址的二级索引=定位的二级菜单的索引
                    recordPositionModel.setLocationIndex(nowSecondPosition);///临时记录定位下来的地址的二级菜单的索引
                }
            }

        }else{
            nowSecondPosition = -1;
        }
        initFirstMenuList(locationAddress);
        if (flag) {
            initSecondMenuList(nowPosition);
        }
        // 执行过此方法，则不是第一次进入，将状态更改为false
        flag = false;
    }
    public void refreshMylocationData( String locationAddress,boolean isOpenLoadtion){
        this.isOpenLoadtion = isOpenLoadtion;
        this.locationAddress = locationAddress;
        initSecondMenuList(nowPosition);
    }

    public void initFirstMenuList(final String locationAddress){
        if(listLeftAreaAdapter == null){
            listLeftAreaAdapter = new ListLeftAreaAdapter(cnt, firstMenuList, nowPosition,locationAddress,
                    new DefaultSelectCallback() {
                        @Override
                        public void callback(int position) {
                            if (flag) {
                                initSecondMenuList(position);
                            }
                            // 执行过此方法，则不是第一次进入，将状态更改为false
                            flag = false;

                        }
                    });
            lv_left_view.setAdapter(listLeftAreaAdapter);
        }else{
            listLeftAreaAdapter.setMyNotifyDataChanged(firstMenuList,nowPosition);
        }
    }
    public void initSecondMenuList(int position){
        nowPosition = position;
        listLeftAreaAdapter.setMyNotifyDataChanged(firstMenuList, nowPosition);
        secondMenuList = hashMap.get(firstMenuList.get(position));
        if(listRightAreaSecondAdapter == null){
            if(TextUtils.isEmpty(recordPositionModel.getSelectAddress())){
                nowSecondPosition = recordPositionModel.getIndex() ;
            }else{
                if(recordPositionModel.getLocalAddress().contains(recordPositionModel.getSelectAddress())){
                    nowSecondPosition = recordPositionModel.getLocationIndex() ;
                }else{
                    nowSecondPosition = recordPositionModel.getIndex() ;
                }
            }
            listRightAreaSecondAdapter = new ListRightAreaSecondAdapter(cnt,secondMenuList,nowSecondPosition);
            lv_right_view.setAdapter(listRightAreaSecondAdapter);
        }else{
            if(TextUtils.isEmpty(recordPositionModel.getSelectAddress())){
                nowSecondPosition = recordPositionModel.getIndex() ;
            }else{
                if(recordPositionModel.getLocalAddress().contains(recordPositionModel.getSelectAddress())){
                    nowSecondPosition = recordPositionModel.getLocationIndex() ;
                }else{
                    nowSecondPosition = recordPositionModel.getIndex() ;
                }
            };
            listRightAreaSecondAdapter.setMyNotifyDataChanged(secondMenuList,nowSecondPosition);
        }
    }
    private OnChecktemLinstener onChecktemLinstener;
    public ShowMyTextSearchPopupWindow regisitMyMenuOnClickListaner(OnChecktemLinstener onChecktemLinstener){
        this.onChecktemLinstener = onChecktemLinstener;
        return  this;
    }

}
